from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.future import select
from app.models.models import User, Conversation, Message, SenderEnum, ContentTypeEnum
from app.database.session import get_db
from app.core.security import get_current_active_user
from app.schemas.message import StoreMessageRequest, MessageResponse
from app.schemas.conversation import ConversationResponse, CreateConversationRequest
from app.utils.oss_service import upload_base64_image
from typing import Optional, List
import datetime

router = APIRouter(prefix="/chat", tags=["对话服务相关"])

# 创建新对话（自动获取当前用户）
@router.post("/conversations", response_model=ConversationResponse)
async def create_conversation(
    req: CreateConversationRequest,
    current_user: User = Depends(get_current_active_user),
    db: AsyncSession = Depends(get_db)
):
    """创建新对话"""
    # 生成对话名称
    #之后可以让ai自动生成一个
    conversation_name = req.name
    if not conversation_name:
        conversation_name = f"新对话 {datetime.datetime.now().strftime('%Y-%m-%d %H:%M')}"
    
    # 创建新对话
    new_conversation = Conversation(
        user_id=current_user.id,
        name=conversation_name
    )
    db.add(new_conversation)
    await db.commit()
    await db.refresh(new_conversation)
    
    return {
        "id": new_conversation.id,
        "name": new_conversation.name,
        "created_at": new_conversation.created_at.isoformat(),
        "message_count": 0
    }

# 获取用户对话历史
@router.get("/conversations", response_model=List[ConversationResponse])
async def get_conversations(
    current_user: User = Depends(get_current_active_user),
    db: AsyncSession = Depends(get_db)
):
    """获取当前用户的对话历史"""
    result = await db.execute(
        select(Conversation).where(Conversation.user_id == current_user.id)
    )
    conversations = result.scalars().all()
    
    # 获取每个对话的消息数量
    conversation_list = []
    for conv in conversations:
        msg_count_result = await db.execute(
            select(Message).where(Message.conversation_id == conv.id)
        )
        msg_count = len(msg_count_result.scalars().all())
        
        conversation_list.append({
            "id": conv.id,
            "name": conv.name,
            "created_at": conv.created_at.isoformat(),
            "message_count": msg_count
        })
    
    return conversation_list

# 获取对话消息
@router.get("/conversations/{conversation_id}/messages", response_model=List[MessageResponse])
async def get_messages(
    conversation_id: int,
    current_user: User = Depends(get_current_active_user),
    db: AsyncSession = Depends(get_db)
):
    """获取指定对话的消息"""
    # 验证对话是否属于当前用户
    conv_result = await db.execute(
        select(Conversation).where(
            Conversation.id == conversation_id,
            Conversation.user_id == current_user.id
        )
    )
    conversation = conv_result.scalar_one_or_none()
    if not conversation:
        raise HTTPException(status_code=404, detail="对话不存在或无权限访问")
    
    result = await db.execute(
        select(Message).where(Message.conversation_id == conversation_id)
    )
    messages = result.scalars().all()
    
    return [
        {
            "id": m.id,
            "sender": m.sender,
            "content_type": m.content_type,
            "content": m.content,
            "oss_urls": m.oss_urls,
            "created_at": m.created_at.isoformat()
        } for m in messages
    ]

# 存储消息（新建对话或追加消息）
@router.post("/store_message", response_model=dict)
async def store_message(
    req: StoreMessageRequest,
    current_user: User = Depends(get_current_active_user),
    db: AsyncSession = Depends(get_db)
):
    """存储消息到对话中"""
    # 处理base64图片上传
    final_oss_urls = []
    
    # 添加已上传的图片URL
    if req.oss_urls:
        final_oss_urls.extend(req.oss_urls)
    
    # 上传base64图片到OSS
    if req.base64_images:
        for base64_img in req.base64_images:
            try:
                oss_url = await upload_base64_image(base64_img)
                final_oss_urls.append(oss_url)
            except Exception as e:
                raise HTTPException(status_code=400, detail=f"图片上传失败: {str(e)}")
    
    # 验证消息内容
    if req.content_type == ContentTypeEnum.text:
        if not req.content:
            raise HTTPException(status_code=400, detail="文本消息必须提供content内容")
        if final_oss_urls:
            raise HTTPException(status_code=400, detail="文本消息不应包含图片")
    elif req.content_type == ContentTypeEnum.image:
        if not final_oss_urls:
            raise HTTPException(status_code=400, detail="图片消息必须提供图片")
        if req.content:
            raise HTTPException(status_code=400, detail="图片消息不应包含文本内容")
    elif req.content_type == ContentTypeEnum.mixed:
        if not req.content:
            raise HTTPException(status_code=400, detail="混合消息必须提供content内容")
        if not final_oss_urls:
            raise HTTPException(status_code=400, detail="混合消息必须提供图片")
    
    conversation_id = req.conversation_id
    
    if conversation_id is None:
        # 新建对话
        new_conversation = Conversation(
            user_id=current_user.id,
            name=f"对话 {datetime.datetime.now().strftime('%Y-%m-%d %H:%M')}"
        )
        db.add(new_conversation)
        await db.commit()
        await db.refresh(new_conversation)
        conversation_id = new_conversation.id
    
    else:
        # 验证现有对话是否属于当前用户
        conv_result = await db.execute(
            select(Conversation).where(
                Conversation.id == conversation_id,
                Conversation.user_id == current_user.id
            )
        )
        conversation = conv_result.scalar_one_or_none()
        if not conversation:
            raise HTTPException(status_code=404, detail="对话不存在或无权限访问")
    
    # 创建新消息
    new_msg = Message(
        conversation_id=conversation_id,
        sender=req.sender,
        content_type=req.content_type,
        content=req.content,
        oss_urls=final_oss_urls if final_oss_urls else None
    )
    db.add(new_msg)
    await db.commit()
    await db.refresh(new_msg)
    
    return {
        "message": "消息存储成功",
        "message_id": new_msg.id,
        "conversation_id": conversation_id,
        "uploaded_images": len(req.base64_images) if req.base64_images else 0
    }

# 删除对话
@router.delete("/conversations/{conversation_id}")
async def delete_conversation(
    conversation_id: int,
    current_user: User = Depends(get_current_active_user),
    db: AsyncSession = Depends(get_db)
):
    """删除对话"""
    # 验证对话是否属于当前用户
    conv_result = await db.execute(
        select(Conversation).where(
            Conversation.id == conversation_id,
            Conversation.user_id == current_user.id
        )
    )
    conversation = conv_result.scalar_one_or_none()
    if not conversation:
        raise HTTPException(status_code=404, detail="对话不存在或无权限访问")
    
    # 删除对话相关的所有消息
    await db.execute(
        Message.__table__.delete().where(Message.conversation_id == conversation_id)
    )
    
    # 删除对话
    await db.execute(
        Conversation.__table__.delete().where(Conversation.id == conversation_id)
    )
    
    await db.commit()
    
    return {"message": "对话删除成功"} 